%%%-------------------------------------------------------------------
%%% @author wukai
%%% @copyright (C) 2017, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 30. 十一月 2017 16:58
%%%-------------------------------------------------------------------
-module(himq_mqtt_ws).
-author("wukai").
-include("himq.hrl").
-export([init/2]).
-export([websocket_init/1]).
-export([websocket_handle/2]).
-export([websocket_info/2]).

init(Req, Opts) ->
  PState = himq_mqtt_codec:p_init(),
  State =#himq_conn{type = ws,p_state = PState},
  case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req) of
    undefined -> {cowboy_websocket, Req, State};
    Subprotocols ->
      case lists:member(<<"mqtt">>, Subprotocols) of
        true ->
          Req2 = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
            <<"mqtt">>, Req),
          {cowboy_websocket, Req2, State};
        false ->
          {stop, Req, State}
      end
  end.

websocket_init(State) ->
  lager:info("websocket state ~p",[State]),
  {ok, State}.
websocket_handle({binary,Bin}, State) ->
  NewState =himq_mqtt:received(State,Bin),
  {ok, NewState}.

%%发送二进制消息
websocket_info({send,Msg}, State) ->
  {{Msg}, State};

%%进程休眠
websocket_info({hibernate,NewState}, _State) ->
  {ok, NewState,hibernate};

websocket_info(Msg, State) ->
  {ok, himq_mqtt_codec:message(Msg,State)};

websocket_info(_Info, State) ->
  {ok, State}.